package com.example.toolproject.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.toolproject.demo.domain.PlanningReport;
import com.example.toolproject.demo.domain.User;
import com.example.toolproject.demo.service.PlanningReportService;
import com.example.toolproject.demo.util.ResultBean;
import com.example.toolproject.demo.util.excel.ExcelUtils;
import com.example.toolproject.demo.util.jwt.JwtUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @ClassName PlanningController
 * @Description TODO
 * @Author lvyongwei
 * @Date 2020-06-28 16:08
 **/
@Controller
@CrossOrigin
@RequestMapping("/planningReport")
public class PlanningReportController {

    @Autowired
    private PlanningReportService planningReportService;

    @Autowired
    private ExcelUtils excelUtils;
    /**
     * 撰写报告
     * @param request
     * @param planningReport   撰写报告实体
     * @return
     */
    @PostMapping("/insertPlanningReport")
    @ResponseBody
    public ResultBean insertPlanningReport(HttpServletRequest request, @RequestBody PlanningReport planningReport){
        //获取前端传来的token
        String token = request.getHeader("Authorization");
        if(token==null || token.equals("")){
            return ResultBean.error("无token,请先登录");
        }
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        //判断token是否失效
        if(u == null){
            return ResultBean.error("token无效");
        }
        //设置用户信息
        planningReport.setUserId(u.getId());
        /**
         * 执行插入操作
         */
        boolean flag=planningReportService.insertPlanReport(planningReport);
        if(flag){
            return ResultBean.success("撰写报告成功");
        }else{
            return ResultBean.error("插入失败");
        }
    }

    /**
     * 根据用户查询策划报告
     * @param request
     * @return
     */
    @GetMapping("/getPlanningReportByUserId")
    @ResponseBody
    public ResultBean getPlanningReportByUserId(HttpServletRequest request){
        //获取前端传来的token
        String token = request.getHeader("Authorization");
        if(token==null || token.equals("")){
            return ResultBean.error("无token,请先登录");
        }
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        //判断token是否失效
        if(u == null){
            return ResultBean.error("token无效");
        }
        int userId=u.getId();
        /**
         * 执行查询操作
         */
        PlanningReport planningReport=planningReportService.getPlanningByUserId(userId);
        if(StringUtils.isEmpty(planningReport) || planningReport==null){
            return ResultBean.error("查询失败");
        }
        return ResultBean.success("查询成功",planningReport);
    }

    /**
     * 查询十条最新的策划报告（不同人）
     * @param request
     * @return
     */
    @GetMapping("/getAllPlanningReportByTime")
    @ResponseBody
    public ResultBean getAllPlanningReportByTime(HttpServletRequest request){
        //获取前端传来的token
        String token = request.getHeader("Authorization");
        if(token==null || token.equals("")){
            return ResultBean.error("无token,请先登录");
        }
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        //判断token是否失效
        if(u == null){
            return ResultBean.error("token无效");
        }
        int userId=u.getId();
        /**
         * 执行查询操作
         */
        List<PlanningReport> planningReports=planningReportService.getAllPlanningReportByTime();
        if(StringUtils.isEmpty(planningReports) || planningReports.size()==0){
            return ResultBean.error("查询失败");
        }
        return ResultBean.success("查询成功",planningReports);
    }

    /**
     * 查询十条分数最高的策划报告
     * @param request
     * @return
     */
    @GetMapping("/getAllPlanningReportByScore")
    @ResponseBody
    public ResultBean getAllPlanningReportByScore(HttpServletRequest request){
        //获取前端传来的token
        String token = request.getHeader("Authorization");
        if(token==null || token.equals("")){
            return ResultBean.error("无token,请先登录");
        }
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        //判断token是否失效
        if(u == null){
            return ResultBean.error("token无效");
        }
        int userId=u.getId();
        /**
         * 执行查询操作
         */
        List<PlanningReport> planningReports=planningReportService.getAllPlanningReportByScore();
        if(StringUtils.isEmpty(planningReports) || planningReports.size()==0){
            return ResultBean.error("查询失败");
        }
        return ResultBean.success("查询成功",planningReports);
    }

    /**
     * 根据撰写的报告的id获取撰写的报告
     * @param planningReportId
     * @return
     */
    @GetMapping("/getPlanningReportById")
    @ResponseBody
    public ResultBean getPlanningReportById(long planningReportId,HttpServletRequest request){
        //获取前端传来的token
        String token = request.getHeader("Authorization");
        if(token==null || token.equals("")){
            return ResultBean.error("无token,请先登录");
        }
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        //判断token是否失效
        if(u == null){
            return ResultBean.error("token无效");
        }
        /**
         * 执行获取撰写报告的方法
         */
        try{
            PlanningReport planningReport=planningReportService.getPlanningReportById(planningReportId);
            return ResultBean.success("获取撰写报告成功",planningReport);
        }catch (Exception e){
            return ResultBean.error("获取撰写报告失败");
        }
    }

    /**
     * 对自己撰写的报告自评成绩
     * @param data
     * @return
     */
    @PostMapping("/updateSelfEvaluation")
    @ResponseBody
    public ResultBean updateSelfEvaluation(@RequestBody String data,HttpServletRequest request){
        //获取前端传来的token
        String token = request.getHeader("Authorization");
        if(token==null || token.equals("")){
            return ResultBean.error("无token,请先登录");
        }
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        //判断token是否失效
        if(u == null){
            return ResultBean.error("token无效");
        }
        /**
         * 获取到两个参数
         */
        JSONObject jsonObject=JSONObject.parseObject(data);
        //撰写的报告的id
        long projectId=jsonObject.getLong("projectId");
        //获取自评分数
        double selfEvaluation=jsonObject.getDouble("selfEvaluation");
        try{
            //执行评分的方法
            boolean flag=planningReportService.updateSelfEvaluation(selfEvaluation,projectId);
            return ResultBean.success("自评成功");
        }catch (Exception e){
            return ResultBean.error("自评失败");
        }
    }

    /**
     * 获取所有策划报告  (不同身份获取信息不同)
     *
     * @param request
     * @param pageNum
     * @param pageSize
     * @param message  搜索条件
     * @return
     */
    @GetMapping("/getAllPlanningReport")
    @ResponseBody
    public ResultBean getAllPlanningReport(HttpServletRequest request, Integer pageNum, Integer pageSize, String message) {
        //获取前端传来的token
        String token = request.getHeader("Authorization");
        if (token == null || token.equals("")) {
            return ResultBean.error("无token,请先登录");
        }
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        //判断token是否失效
        if (u == null) {
            return ResultBean.error("token无效");
        }
        if (StringUtils.isEmpty(pageNum) || pageNum == 0) {
            pageNum = 1;
        }
        if (StringUtils.isEmpty(pageSize) || pageSize == 0) {
            pageSize = 10;
        }
        /**
         * 执行分页
         */
        try {
            PageHelper.startPage(pageNum, pageSize);
            List<PlanningReport> planningReports = null;
            /**
             * 判断用户身份
             */
            //即管理员用户
            if (u.getRoleId().equals(1)) {
                planningReports = planningReportService.getAllPlanningReport(null,null,message);
                if(StringUtils.isEmpty(planningReports) || planningReports.size()==0){
                    return ResultBean.error("没有策划报告信息");
                }
            } else if (u.getRoleId().equals(2)) {
                //即教师身份
                planningReports = planningReportService.getAllPlanningReport(null,null,message);
                if(StringUtils.isEmpty(planningReports) || planningReports.size()==0){
                    return ResultBean.error("没有试验报告信息");
                }
            } else {
                planningReports = planningReportService.getAllPlanningReport(u.getId(),null,message);
                if(StringUtils.isEmpty(planningReports) || planningReports.size()==0){
                    return ResultBean.error("学生没有提交实验报告信息");
                }
            }
            PageInfo<PlanningReport> pageInfo = new PageInfo<PlanningReport>(planningReports);
            return ResultBean.success("获取到用户实验报告数据", pageInfo);
        } catch (Exception e) {
            return ResultBean.error("没有获取到实验报告信息");
        }
    }

    /**
     * 删除策划报告数据
     * @param request
     * @param data
     * @return
     */
    @PostMapping("/deletePlanningReport")
    @ResponseBody
    public ResultBean deletePlanningReport(HttpServletRequest request, @RequestBody String data){
        //获取前端传来的token
        String token = request.getHeader("Authorization");
        if (token == null || token.equals("")) {
            return ResultBean.error("无token,请先登录");
        }
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        //判断token是否失效
        if (u == null) {
            return ResultBean.error("token无效");
        }
        /**
         * 解析json数据
         */
        JSONObject jsonObject=JSONObject.parseObject(data);
        /**
         * 获取策划报告id
         */
        long planningReportId = jsonObject.getLong("planningReportId");
        try{
            planningReportService.deletePlanningReport(planningReportId);
            return ResultBean.success("删除成功");
        }catch (Exception e){
            return ResultBean.error("删除失败");
        }
    }

    /**
     * 获取所有策划报告  (不同身份获取信息不同)
     * @return
     */
    @GetMapping("/export")
    public void getAllPlanningReport(HttpServletRequest request, HttpServletResponse response,String token) {
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        try {
            List<PlanningReport> planningReports = null;
            /**
             * 判断用户身份
             */
            //即管理员用户
            if (u.getRoleId().equals(1)) {
                planningReports = planningReportService.getAllPlanningReport(null,null,null);
            } else if (u.getRoleId().equals(2)) {
                //即教师身份
                planningReports = planningReportService.getAllPlanningReport(null,null,null);
            } else {
                planningReports = planningReportService.getAllPlanningReport(u.getId(),null,null);
            }
            excelUtils.cooperationData(request,response,planningReports,"用户策划报告数据",PlanningReport.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
